<template>
  <div class="user-management-container">
    <!-- 顶部标题和操作区 -->
    <div class="header-section">
      <div class="title-section">
        <h2 class="page-title">
          <i class="el-icon-user"></i>
          用户管理系统
        </h2>
        <div class="action-area">
          <el-input
            placeholder="搜索用户名/手机号/邮箱"
            v-model="searchKey"
            class="search-input"
            clearable
            @clear="getList"
            @keyup.enter.native="getList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getList"
              class="search-btn"
            ></el-button>
          </el-input>
          <el-button
            @click="addUser"
            type="primary"
            icon="el-icon-plus"
            class="add-btn"
          >
            新增用户
          </el-button>
        </div>
      </div>
    </div>

    <!-- 用户表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        class="user-table"
        v-loading="loading"
        element-loading-text="数据加载中..."
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column label="序号" width="80" align="center">
          <template slot-scope="scope">
            <span class="index-number">{{
              (cp - 1) * pageSize + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="userName"
          label="用户名"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            <span class="user-name">{{ scope.row.userName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="密码" width="180" align="center">
          <template slot-scope="scope">
            <span class="password">******</span>
            <el-tooltip content="点击查看密码" placement="top">
              <el-button
                type="text"
                icon="el-icon-view"
                @click="showPassword(scope.row)"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column
          prop="userPhoneNumber"
          label="手机号"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            <span class="phone">{{ scope.row.userPhoneNumber }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="roleType"
          label="角色"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.roleType === 'admin' ? 'danger' : 'success'"
            >
              {{ scope.row.roleType === "admin" ? "管理员" : "普通用户" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="recommendType"
          label="推荐类型"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="getRecommendTagType(scope.row.recommendType)">
              {{ getRecommendLabel(scope.row.recommendType) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="email" label="邮箱">
          <template slot-scope="scope">
            <span class="email">{{ scope.row.email }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template slot-scope="scope">
            <el-tooltip content="编辑用户" placement="top">
              <el-button
                @click.native.prevent="editor(scope)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                circle
              ></el-button>
            </el-tooltip>

            <el-tooltip content="删除用户" placement="top">
              <el-button
                @click.native.prevent="_delete(scope)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        @current-change="changeCP"
        :current-page="cp"
        :page-size="pageSize"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog
      :title="userInfo.id ? '编辑用户信息' : '新增用户'"
      :visible.sync="registerDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      custom-class="custom-dialog"
      @closed="handleDialogClose"
    >
      <div class="dialog-content">
        <div class="dialog-header">
          <i class="el-icon-user-solid"></i>
          <span>{{ userInfo.id ? "编辑用户信息" : "创建新用户" }}</span>
        </div>

        <el-form
          ref="userForm"
          :model="form"
          :rules="rules"
          label-position="top"
          class="dialog-form"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="form.userName"
              placeholder="请输入用户名"
              prefix-icon="el-icon-user"
            ></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              show-password
            ></el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="form.phone"
              placeholder="请输入手机号"
              prefix-icon="el-icon-mobile-phone"
            >
              <template slot="prepend">+86</template>
            </el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="form.email"
              placeholder="请输入邮箱"
              prefix-icon="el-icon-message"
            ></el-input>
          </el-form-item>

          <el-form-item label="用户角色" prop="role">
            <el-select
              v-model="form.role"
              placeholder="请选择用户角色"
              style="width: 100%"
            >
              <el-option label="普通用户" value="user"></el-option>
              <el-option label="管理员" value="admin"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="用户喜好推荐" prop="recommendType">
            <el-select
              v-model="form.recommendType"
              placeholder="请选择推荐类型"
              style="width: 100%"
            >
              <el-option
                v-for="item in recommendOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="registerDialogVisible = false" class="cancel-btn"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="submitForm"
          class="submit-btn"
          :loading="submitting"
        >
          {{ userInfo.id ? "保 存" : "创 建" }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 密码查看弹窗 -->
    <el-dialog
      title="用户密码信息"
      :visible.sync="passwordDialogVisible"
      width="35%"
      custom-class="password-dialog"
    >
      <div class="password-content">
        <div class="password-card">
          <div class="password-header">
            <i class="el-icon-key"></i>
            <span>用户密码详情</span>
          </div>

          <div class="password-body">
            <div class="password-item">
              <span class="label">用户名:</span>
              <span class="value">{{ currentUser.userName }}</span>
            </div>

            <div class="password-item">
              <span class="label">密码:</span>
              <span class="value password-text">{{
                currentUser.password
              }}</span>
              <el-tooltip content="复制密码" placement="top">
                <el-button
                  type="text"
                  icon="el-icon-document-copy"
                  @click="copyPassword"
                  class="copy-btn"
                ></el-button>
              </el-tooltip>
            </div>

            <div class="password-tip">
              <i class="el-icon-warning"></i>
              <span>请注意保护用户隐私，不要泄露密码信息</span>
            </div>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false" class="close-btn"
          >关 闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      cp: 1,
      pageSize: 10,
      total: 0,
      registerDialogVisible: false,
      passwordDialogVisible: false,
      userInfo: {},
      searchKey: "",
      loading: false,
      submitting: false,
      currentUser: {},
      form: {
        userName: "",
        password: "",
        phone: "",
        email: "",
        role: "user",
        recommendType: "hybrid",
      },
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 16,
            message: "长度在 3 到 16 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
        recommendType: [
          { required: true, message: "请选择推荐类型", trigger: "change" },
        ],
      },
      recommendOptions: [
        { value: "content-based", label: "基于内容的推荐" },
        { value: "popular", label: "基于热销的推荐" },
        { value: "random", label: "随机推荐" },
        { value: "hybrid", label: "混合推荐" },
        { value: "new-arrivals", label: "新书推荐" },
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      this.$axios
        .post("/api/admin/getAllUser", {
          cp: this.cp,
          searchKey: this.searchKey,
        })
        .then((res) => {
          this.tableData = res.data.data.data || [];
          this.total = res.data.data.total || 0;
        })
        .catch(() => {
          this.$message.error("获取用户列表失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    changeCP(index) {
      this.cp = index;
      this.getList();
    },

    addUser() {
      this.userInfo = {};
      this.form = {
        userName: "",
        password: "",
        phone: "",
        email: "",
        role: "user",
        recommendType: "hybrid",
      };
      this.registerDialogVisible = true;
    },

    editor(row) {
      this.userInfo = {
        id: row.row.user_id,
        userName: row.row.userName,
        password: row.row.password,
        phone: row.row.userPhoneNumber,
        email: row.row.email,
        role: row.row.roleType,
        recommendType: row.row.recommendType || "hybrid",
      };
      this.form = {
        userName: row.row.userName,
        password: row.row.password,
        phone: row.row.userPhoneNumber,
        email: row.row.email,
        role: row.row.roleType,
        recommendType: row.row.recommendType || "hybrid",
      };
      this.registerDialogVisible = true;
    },

    _delete(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .post("/api/admin/deleteUser", {
              user_id: row.row.user_id,
            })
            .then((res) => {
              if (res.data.code == "001") {
                this.$message.success(res.data.msg);
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            });
        })
        .catch(() => {});
    },

    showPassword(user) {
      this.currentUser = user;
      this.passwordDialogVisible = true;
    },

    handleDialogClose() {
      this.$refs.userForm.resetFields();
    },

    submitForm() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.submitting = true;
          const api = this.userInfo.id
            ? "/api/admin/updateUser"
            : "/api/admin/addUser";
          const params = {
            ...this.form,
            phoneNum: this.form.phone,
            type: this.form.recommendType,
            user_id: this.userInfo.id || undefined,
          };

          this.$axios
            .post(api, params)
            .then((res) => {
              if (res.data.code === "001") {
                this.$message.success(res.data.msg);
                this.registerDialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch(() => {
              this.$message.error("操作失败，请稍后重试");
            })
            .finally(() => {
              this.submitting = false;
            });
        }
      });
    },

    copyPassword() {
      const password = this.currentUser.password;
      navigator.clipboard
        .writeText(password)
        .then(() => {
          this.$message.success("密码已复制到剪贴板");
        })
        .catch(() => {
          this.$message.error("复制失败");
        });
    },

    getRecommendLabel(type) {
      const option = this.recommendOptions.find((item) => item.value === type);
      return option ? option.label : "未知类型";
    },

    getRecommendTagType(type) {
      const map = {
        "content-based": "primary",
        popular: "success",
        random: "info",
        hybrid: "warning",
        "new-arrivals": "danger",
      };
      return map[type] || "";
    },
  },
};
</script>

<style lang="less" scoped>
.user-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.header-section {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

  .title-section {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      margin: 0;
      font-size: 18px;
      color: #333;
      display: flex;
      align-items: center;

      i {
        margin-right: 10px;
        font-size: 20px;
        color: #409eff;
      }
    }

    .action-area {
      display: flex;
      align-items: center;

      .search-input {
        width: 300px;
        margin-right: 15px;

        ::v-deep .el-input__inner {
          border-top-right-radius: 0;
          border-bottom-right-radius: 0;
        }
      }

      .search-btn {
        background-color: #409eff;
        color: white;
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;

        &:hover {
          background-color: #66b1ff;
        }
      }

      .add-btn {
        padding: 10px 15px;
      }
    }
  }
}

.table-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  margin-bottom: 20px;

  .user-table {
    border-radius: 4px;
    overflow: hidden;

    ::v-deep th {
      background-color: #f8f8f9 !important;
      font-weight: 600;
      color: #515a6e;
    }

    .index-number {
      color: #909399;
    }

    .user-name {
      font-weight: 500;
      color: #333;
    }

    .password {
      margin-right: 10px;
      color: #999;
    }

    .phone,
    .email {
      color: #666;
    }
  }
}

.pagination-container {
  text-align: right;
  padding: 10px 0;
}

/* 自定义弹窗样式 */
::v-deep .custom-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);

  .el-dialog__header {
    border-bottom: 1px solid #f0f0f0;
    padding: 15px 20px;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .el-dialog__headerbtn {
      top: 15px;
    }
  }

  .dialog-content {
    padding: 20px;

    .dialog-header {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      i {
        font-size: 24px;
        color: #409eff;
        margin-right: 10px;
      }

      span {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }

    .dialog-form {
      .el-form-item {
        margin-bottom: 22px;

        .el-form-item__label {
          padding-bottom: 8px;
          font-weight: 500;
          color: #555;
        }
      }
    }
  }

  .dialog-footer {
    padding: 10px 20px;
    border-top: 1px solid #f0f0f0;

    .cancel-btn {
      padding: 10px 20px;
      border-radius: 4px;
    }

    .submit-btn {
      padding: 10px 20px;
      border-radius: 4px;
      background-color: #409eff;
      border-color: #409eff;

      &:hover {
        background-color: #66b1ff;
        border-color: #66b1ff;
      }
    }
  }
}

/* 密码弹窗样式 */
::v-deep .password-dialog {
  border-radius: 8px;

  .el-dialog__header {
    border-bottom: 1px solid #f0f0f0;
    padding: 15px 20px;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .password-content {
    padding: 0 20px;

    .password-card {
      background-color: #f9fafc;
      border-radius: 6px;
      padding: 20px;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);

      .password-header {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px dashed #e6e6e6;

        i {
          font-size: 22px;
          color: #e6a23c;
          margin-right: 10px;
        }

        span {
          font-size: 16px;
          font-weight: 500;
          color: #333;
        }
      }

      .password-body {
        .password-item {
          display: flex;
          align-items: center;
          margin-bottom: 15px;

          .label {
            width: 80px;
            font-weight: 500;
            color: #666;
          }

          .value {
            flex: 1;
            color: #333;

            &.password-text {
              font-family: monospace;
              font-size: 16px;
              letter-spacing: 1px;
              color: #409eff;
            }
          }

          .copy-btn {
            margin-left: 10px;
            color: #409eff;
          }
        }

        .password-tip {
          margin-top: 20px;
          padding: 10px;
          background-color: #f0f7ff;
          border-radius: 4px;
          display: flex;
          align-items: center;

          i {
            color: #e6a23c;
            margin-right: 8px;
          }

          span {
            color: #666;
            font-size: 14px;
          }
        }
      }
    }
  }

  .dialog-footer {
    padding: 10px 20px;
    border-top: 1px solid #f0f0f0;

    .close-btn {
      padding: 10px 20px;
      border-radius: 4px;
    }
  }
}
</style>
